<template>
  <!-- <div> -->
  <div class="modal" v-show="visibility">
    <!-- 增加这个盒子是为了阻止冒泡 -->
    <div class="modal_bg" @click="close"></div>
    <div class="modal_content">
      <img src="../assets/img/close.png" alt @click="close" />

      <section class="nav">
        <!-- 手机登录 -->
        <a href="#" :class="{ active: isshow }" @click="isshow = true">手机号码登录</a> |
        <!-- 二维码登录 -->
        <a href="#" :class="{ active: !isshow }" @click="weixinClick">二维码扫码登录</a>
      </section>

      <div class="content">
        <div class="plonelogin" v-show="isshow">
          <div class="row">
            <input type="text" class="ipt" placeholder="请输入手机号" v-model="ploneNum" />
          </div>
          <!-- 拼图验证码 -->
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" class="ipt" placeholder="请输入短信验证码" v-model="SMSCode" />
            <button class="btn qrbtn" @click="getCode" v-show="!isshowCount">获取验证码</button>
            <button class="btn qrbtn" v-show="isshowCount">{{ `${count}s` }}</button>
          </div>
          <div class="row">
            <button class="btn loginbtn" @click="submitFn">登录</button>
          </div>
        </div>
        <div id="weixin" class="qrlogin" v-show="!isshow">二维码登录</div>
      </div>
    </div>
  </div>
  <!-- </div> -->
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex"
import { getPloneCodeApi, ploneLoginApi, PloneBindWeixinApi, userProfilesApi } from "../request/api"
import { validataPloneNum } from "../utils"

export default {
  data() {
    return {
      isshow: true,
      msg: "向右滑动",
      ploneNum: "",
      isshowCount: false,//控制获取验证码按钮的内容显示
      count: 6,//显示的读秒数字
      SMSCode: ""//短信验证码

    }
  },

  created() {
  },
  computed: {
    ...mapState({
      visibility: state => state.login.visibility
    })
  },

  methods: {
    ...mapMutations({
      toLogin: "login/toLogin",
      chanIsLogined: "loginStatus/chanIsLogined",
      chanIsShowToast: "toastStatus/chanIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "toastStatus/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 手机号码和拼图验证的函数封装
    toVertify() {
      if (!validataPloneNum(this.ploneNum)) {
        this.asyncIsShowToast({
          isShowToast: true,
          toastMsg: "请输入正确的手机号码",
          toastType: "danger"
        })
        return false;
      }
      // 没有滑动滑块或者滑动滑块错误了
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        this.asyncIsShowToast({
          isShowToast: true,
          toastMsg: "请进行滑块验证",
          toastType: "danger"
        })
        return false;
      }
      return true;
    },
    // 这是读秒的函数封装
    countdown() {
      this.isshowCount = true
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer)
          this.isshowCount = false
          this.count = 6;
        }
      }, 1000)
    },

    // 点击登录按钮
    async submitFn() {
      // 点击登录也要验证手机号码拼图以及短信验证码
      if (!this.toVertify()) return;
      if (this.SMSCode.trim() === "") {
        alert("请输入手机验证码")
        return
      }
      // 发起登录请求
      let uuid = localStorage.getItem("uuid")
      let res = null;
      if (uuid) {
        // 407这种情况的登录   手机号绑定微信的请求
        res = await PloneBindWeixinApi({
          phone: this.ploneNum.trim(),
          verifyCode: this.SMSCode.trim(),
          uuid,
        })
      } else {
        // 正常请求
        res = await ploneLoginApi({
          verifyCode: this.SMSCode.trim(),
          phone: this.ploneNum.trim(),
        })
      }


      if (!res) return;
      // 登录成功之后的逻辑
      // 1.关闭登录窗口
      this.toLogin(false)
      // 2.提示登录成功
      alert("登录成功!")
      // 3.存储token值
      localStorage.setItem("x-auth-token", res["x-auth-token"])
      // 4.登录状态的切换
      this.chanIsLogined(true)
      // 5。清除uuid
      localStorage.removeItem(uuid)
      // 6.清除url中的code
      this.$router.push(this.$route.path)

      // 发起获取用户信息
      // let userProfiles = userProfilesApi()
      this.asyncChangeUserInfo()

    },

    // 点击获取验证码按钮
    async getCode() {
      // 1.验证手机号和拼图
      if (!this.toVertify()) return;
      this.countdown()
      //2.请求验证码
      let res = await getPloneCodeApi({
        plone: this.ploneNum.trim()
      })
      if (!res) return;
      if (res.code === 0) {
        alert("发送手机验证码成功")
      }
      console.log(res);
    },
    // 显示微信二维码并生成二维码
    weixinClick() {
      this.isshow = false
      let _this = this;
      new WxLogin({//创建一个二维码实例
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d",  // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(window.btoa("http://127.0.0.1:8080" + _this.$route.path)),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICBkaXNwbGF5OiBub25lOw0KfQ",
      });
    },

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    close() {
      this.toLogin(false)
    }
  }
}
</script>
 
<style lang = "less" scoped>
.modal {
  //整个模态框的样式
  position: fixed; //这个定位是为了让他在首页的上层显示，而不是在footer的下面显示
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  .modal_bg {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .modal_content {
    width: 555px;
    height: 423px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    background: url("../assets/img/login-box-bg.png");
    img {
      position: absolute;
      top: 10px;
      right: 60px;
      cursor: pointer;
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 40px;
      a {
        padding: 0 10px;
        text-decoration: none;
        &.active {
          color: blue;
        }
      }
    }
    .content {
      width: 355px;
      height: 200px;
      margin: 20px auto 0;
      .plonelogin {
        .row {
          display: flex;
          margin-bottom: 20px;
          .ipt {
            width: 100%;
            height: 48px;
            flex: 1;
            outline: none;
          }
          .btn {
            background-color: #0a328e;
            color: #fff;
            line-height: 48px;
            cursor: pointer;
          }
          .qrbtn {
            margin-left: 10px;
          }
          .loginbtn {
            width: 100%;
          }
        }
      }
      #weixin {
        display: flex;
        justify-content: center;
      }
    }
  }

  /deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
      position: absolute;
      left: 0;
      top: -120px;
      display: none;
      width: 100%;
      box-sizing: border-box;
    }
    .slide-verify-block {
      width: 85px;
      height: 136px;
    }
    .slide-verify-refresh-icon {
      top: -120px;
      display: none;
    }
    &:hover {
      canvas {
        display: block;
      }
      .slide-verify-refresh-icon {
        display: block;
      }
    }
  }
}
</style>